package com.situ.tos2024.util;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能：枚举类型转换器
 *
 * @author 千堆雪
 * @version 1.0.0
 * @since 2024/4/9
 * <p>
 * created by 千堆雪 on 2024/4/9 15:16, last modified by 千堆雪 on 2024/4/9 15:16
 */
public class EnumTypeHandler<E extends Enum<E> & AbstractEnum> extends BaseTypeHandler<E> {
    private final Map<String, E> caches = new HashMap<>();

    public EnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("枚举类型不可为空");
        }
        for (E e : type.getEnumConstants()) {
            caches.put(e.getName(), e);
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E e, JdbcType jdbcType) throws SQLException {
        if (jdbcType == null) {
            ps.setString(i, e.getName());
        } else {
            ps.setObject(i, e.getName(), jdbcType.TYPE_CODE);
        }
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return caches.get(rs.getString(columnName));
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return caches.get(rs.getString(columnIndex));
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return caches.get(cs.getString(columnIndex));
    }
}
